const express = require('express')
const multer = require('multer')
const Result = require('../utils/Result');
const { saveToLocal, delLocalFile } = require('../service/uploadService');

const router = express.Router()
const upload = multer({ storage: multer.memoryStorage() })

router.post('/upload', upload.single('file'), async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ code: 1, message: '未上传文件' })
  }

  try {
    const result = await saveToLocal(req.file)
    res.json(Result.success(result, '上传成功'))
  } catch (err) {
    res.json(Result.fail('上传失败'))
  }
})

router.post('/clean-image', async (req, res) => {
  const { image_url } = req.body;

  if (!image_url) {
    return res.json(Result.fail('缺少参数 image_url'));
  }

  const knex = getKnex();

  try {
    const exists = await knex('project_images')
      .where({ image_url })
      .first();

    if (exists) {
      return res.json(Result.success('图片仍被数据库引用，未执行删除'));
    }

    const deleted = await delLocalFile(image_url);

    if (deleted) {
      res.json(Result.success('文件已成功删除或不存在'));
    } else {
      res.json(Result.fail('文件删除失败'));
    }
  } catch (err) {
    console.error('[清理图片接口出错]', err);
    res.json(Result.fail('服务器异常'));
  }
});

module.exports = router
